package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.config.WebChatConstants;
import com.qianniu.napi.common.util.*;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2019-04-11
 */
@Controller
public class KehuController {

    private static final Logger logger = LoggerFactory.getLogger(KehuController.class);

    @Autowired
    private IKehuService kehuService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IBannerService bannerService;
    @Autowired
    private IStoreService storeService;

    @RequestMapping("admin/kehu/index")
    public String index(Model model) {
        List<Area> shenglist = areaService.selectList(new EntityWrapper<Area>().setSqlSelect("code,name").eq("level", 1));
        List<Area> shilist = new ArrayList<Area>();
        Area em = new Area();
        em.setCode("");
        em.setName("请选择市区");
        shilist.add(em);

        shilist.addAll(areaService.selectList(new EntityWrapper<Area>().setSqlSelect("code,name").eq("sheng", "11").eq("level", 3)));
        model.addAttribute("shenglist", shenglist);
        model.addAttribute("shilist", shilist);

        model.addAttribute("hylist", configService.selectList(new EntityWrapper<Config>().setSqlSelect("code,name")
                .eq("pcode", "khhangye").orderBy("sort")));

        return "admin/kehu";
    }

    @RequestMapping("/admin/kehu/list")
    @ResponseBody
    public Page<Kehu> list(@RequestParam(value = "offset", required = false) Integer offset,
                           @RequestParam(value = "status", required = false) String status,
                           @RequestParam(value = "search", required = false) String search,
                           @RequestParam(value = "sheng", required = false) String sheng,
                           @RequestParam(value = "shi", required = false) String shi,
                           @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<Kehu> wrapper = new EntityWrapper<Kehu>();
        String wheresql = " 1=1 ";
        if (!Strings.isNullOrEmpty(sheng))
            wheresql += " and areacode = " + sheng;
        if (!Strings.isNullOrEmpty(shi))
            wheresql += " and shicode = " + shi;

        if (!Strings.isNullOrEmpty(search))
            wrapper.andNew().like("mname", search).or().like("phone", search).or().like("telephone", search);

//        wrapper.where(wheresql);

        wrapper.orderBy("id", true);
        Page<Kehu> page = kehuService.selectPage(new Page<Kehu>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/kehu/add")
    @ResponseBody
    public Jinfo add(@Valid Kehu bean, Model model) {
        // 字段校验
        Jinfo jinfo = new Jinfo();

        bean.setModifytime(new Date());

        User user = (User) SecurityUtils.getSubject().getPrincipal();
        logger.debug("==============");
        bean.setCreatetime(new Date());
        bean.setModifier(user.getId());
        bean.setModifyname(user.getName());
        Config config = configService.selectOne(new EntityWrapper<Config>().eq("code", bean.getHytype()));
        if (config != null) bean.setHyname(config.getName());

        bean.insert();

        return jinfo;
    }

    @RequestMapping("/admin/kehu/getKehuById")
    @ResponseBody
    public Kehu getKehuById(long id) {
        Kehu kehu = kehuService.selectById(id);
        return kehu;
    }

    @RequestMapping("/admin/kehu/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = kehuService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/kehu/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        Kehu bean = new Kehu();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        kehuService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/kehu/modify")
    @ResponseBody
    public Jinfo update(Kehu bean) {
        Jinfo jinfo = new Jinfo();
        try {
            if (bean.getHyname() != null && bean.getHyname().length() > 0)
                bean.setHytype(PinyinHelper.convertToPinyinString(bean.getHyname(), "", PinyinFormat.WITHOUT_TONE));
        } catch (Exception e) {
            logger.error("==========convertToPinyinString error", e);
        }
        Config config = configService.selectOne(new EntityWrapper<Config>().eq("code", bean.getHytype()));
        if (config != null) bean.setHyname(config.getName());

        bean.setModifytime(new Date());
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        logger.debug("==============user=" + user);

        bean.setModifier(user.getId());
        bean.setModifyname(user.getName());
        kehuService.updateById(bean);
        return jinfo;
    }

    @RequestMapping("/admin/kehu/addfile")
    @ResponseBody
    public Jinfo update(String hytype,
                        String area,
                        String areacode,
                        String shi,
                        String shicode,
                        String path
    ) {
        Jinfo jinfo = new Jinfo();

        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String, String>> list = null;
        String cellData = null;
        String columns[] = {"id", "mname", "phone", "telephone", "address"};

        wb = ReadExcel.readExcel(path);
        if (wb != null) {
            //用来存放表中数据
            list = new ArrayList<Map<String, String>>();
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = row.getPhysicalNumberOfCells();
            for (int i = 1; i < rownum; i++) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                row = sheet.getRow(i);
                if (row != null) {
                    for (int j = 0; j < colnum; j++) {
                        cellData = (String) ReadExcel.getCellFormatValue(row.getCell(j));
                        map.put(columns[j], cellData);
                    }
                } else {
                    break;
                }
                list.add(map);
            }
        }

//        String[] areas = area.split("@");
//        Area sheng = areaService.selectOne(new EntityWrapper<Area>()
//                .setSqlSelect("name,code,sheng")
//                .like("name", areas[0]));
//
//        Area shi = null;
//        if(areas.length==2){
//            Wrapper<Area> wrapper = new EntityWrapper<Area>().setSqlSelect("name,code").like("name", areas[1]);
//            if(sheng!=null)wrapper.eq("sheng",sheng.getSheng());
//            shi = areaService.selectOne(wrapper);
//        }

        //遍历解析出来的list
        for (Map<String, String> map : list) {
            Kehu kehu = new Kehu();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.print(entry.getKey() + ":" + entry.getValue() + ",");

                if (entry.getKey().equals("mname")) {
                    kehu.setMname(entry.getValue());
                } else if (entry.getKey().equals("phone")) {
                    kehu.setPhone(entry.getValue());

                } else if (entry.getKey().equals("telephone")) {
                    kehu.setTelephone(entry.getValue());

                } else if (entry.getKey().equals("address")) {
                    kehu.setAddress(entry.getValue());
                }

                Config config = configService.selectOne(new EntityWrapper<Config>().eq("code", hytype));
//                kehu.setHyname(hyname);
                kehu.setHyname(config.getName());
//                try {
//                    kehu.setHytype(PinyinHelper.convertToPinyinString(hyname, "", PinyinFormat.WITHOUT_TONE));
//                }catch (Exception e){
//                    logger.error("==========convertToPinyinString error",e);
//                }
                kehu.setState(1);

                kehu.setArea(area);
                kehu.setAreacode(areacode);
                kehu.setShi(shi);
                kehu.setShicode(shicode);
            }

            Wrapper<Kehu> wrapper = new EntityWrapper<Kehu>().eq("areacode", kehu.getAreacode()).eq("mname", kehu.getMname());
            int kehuone = kehuService.selectCount(wrapper);

            if (kehuone == 1) {
                Kehu kh = kehuService.selectOne(wrapper);
                if (kehu.getPhone() != null &&
                        (kh.getPhone() == null || kh.getPhone().equals("") || kh.getPhone().replaceAll(" ", "").length() == 0)) {
                    kh.setPhone(kehu.getPhone());
                }
                if (kehu.getTelephone() != null &&
                        (kh.getTelephone() == null || kh.getTelephone().equals("") || kh.getTelephone().replaceAll(" ", "").length() == 0)) {
                    kh.setTelephone(kehu.getTelephone());
                }
                if (kehu.getAddress() != null &&
                        (kh.getTelephone() == null || kh.getTelephone().equals("") || kh.getTelephone().replaceAll(" ", "").length() == 0) ||
                        kehu.getAddress().indexOf(kh.getAddress()) >= 0) {
                    kh.setAddress(kehu.getAddress());
                }
                if (kehu.getShi() != null) kh.setShi(kehu.getShi());
                if (kehu.getShicode() != null) kh.setShicode(kehu.getShicode());

                kh.updateById();
            } else {
                kehu.insert();
            }
        }

        return jinfo;
    }


    @RequestMapping(value = "/admin/upload/khexcel", method = RequestMethod.POST)
    @ResponseBody
    public JsonDO uploadKhexcel(@RequestParam(value = "mfile", required = true) MultipartFile mfile,
                                @RequestParam(value = "t", required = false) String t,
                                @RequestParam(value = "type", required = true) String type) {

        JsonDO json = new JsonDO();
        if (mfile != null) {

            String fileName = mfile.getOriginalFilename();
            logger.debug(">>>mediafile=" + fileName);

            String rfilename = fileName.substring(0, fileName.lastIndexOf("."));
            if (rfilename.length() > 16) rfilename = rfilename.substring(0, 16);
            String extname = fileName.substring(fileName.lastIndexOf(".") + 1);
            String[] ts = type.split("_");
            String tyth = ts.length == 2 ? ts[0] + "/" + ts[1] + "/" : ts[0] + "/";
            Merchant mch = redisService.getMerchant(ObjectUtil.getMid());
            String mcode = mch == null ? "admin" : mch.getMcode();
            String dirpath = Constants.IMG_UPLOAD_PATH + mcode + "/" + tyth;

            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            Date date = new Date();
//            String filename = EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname;
            String newfname = "";
            try {
                newfname = StringUtil.isContainChinese(rfilename) ? PinyinHelper.convertToPinyinString(rfilename, "", PinyinFormat.WITHOUT_TONE) : rfilename;
                newfname = newfname.replaceAll(" ", "").replaceAll("、", "").replaceAll("-", "");
                logger.debug(">>>after convertToPinyinString newfname=" + newfname);
            } catch (Exception e) {
                logger.error(">>>tpinyin error", e);
            }

            newfname = Strings.isNullOrEmpty(newfname) ? EncryptUtil.md5(date.getTime() + fileName).substring(0, 16) : newfname;
            if (newfname.length() > 16) newfname = newfname.substring(0, 16);

//            File file = new File(dirpath + EncryptUtil.md5(date.getTime()+fileName).substring(0,16)+"."+extname);// 保持原有文件格式
            File file = new File(dirpath + newfname + "." + extname);// 保持原有文件格式
            if (file.exists()) {
                newfname = EncryptUtil.md5(date.getTime() + fileName).substring(0, 16);
                file = new File(dirpath + newfname + "." + extname);
            }
            logger.debug(">>>targetFile getAbsolutePath=" + file.getAbsolutePath());
            FileOutputStream outputStream = null;
            InputStream inputStream = null;
            //保存
            try {
                file.createNewFile();
                logger.debug(">>>start to FileOutputStream");

                outputStream = new FileOutputStream(file);
                inputStream = mfile.getInputStream();
                byte temp[] = new byte[1024];
                int size = -1;
                while ((size = inputStream.read(temp)) != -1) { // 每次读取1KB，直至读完
                    logger.info("File load size=" + size);
                    outputStream.write(temp, 0, size);
                }

                logger.info("File load success.");
            } catch (IOException e) {
                logger.warn("File load fail.", e);
            } finally {
                try {
                    outputStream.close();
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("IO close error", e);
                }
            }


            String imgurl = Constants.IMG_UPLOAD_HOST + mcode + "/" + tyth + file.getName();
            logger.info("===========================imgurl=" + file.getPath());
            json.setData(file.getPath());

        }

        json.setMsg("ok");
        return json;
    }

    @RequestMapping(value = "/test/upload/kdexcel", method = RequestMethod.POST)
    @ResponseBody
    public JsonDO uploadkdexcel(@RequestParam(value = "type", required = true) String type,
                                String path) {

        JsonDO json = new JsonDO();

        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String, String>> list = null;
        String cellData = null;
        String columns[] = {"name", "code"};
        Config config = null;

        wb = ReadExcel.readExcel(path);
        if (wb != null) {
            //用来存放表中数据
            list = new ArrayList<Map<String, String>>();
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = row.getPhysicalNumberOfCells();
            for (int i = 2; i < rownum; i++) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                config = new Config();
                config.setIsSystem(1);
                config.setLevel(1);
                config.setPid(2648l);
                config.setPcode("kuaidibianma");
                row = sheet.getRow(i);
                if (row != null) {
                    for (int j = 0; j < colnum; j++) {
                        cellData = (String) ReadExcel.getCellFormatValue(row.getCell(j));
                        if (j == 0) config.setName(cellData);
                        if (j == 1) config.setCode(cellData);
                    }
                    config.insert();
                } else {
                    break;
                }
                list.add(map);
            }
        }

        return json;
    }


    @RequestMapping(value = "/test/userqr")
    public ModelAndView userqr(HttpServletRequest request,
                               Model model,
                               HttpServletResponse response) throws Exception {

        ModelAndView mv = new ModelAndView("test/userqr");

        String redirect_uri = URLEncoder.encode(WebChatConstants.REDIRECT_URL + "29");
        logger.info("========================redirect_uri=" + redirect_uri);
//        String authurl = WebChatConstants.GET_OPENID_URL.replace("REDIRECT_URI",redirect_uri).replace("APPID",WebChatConstants.APPID);
        String authurl = WebChatConstants.GET_OPENID_URL.replace("REDIRECT_URI", redirect_uri).replace("APPID", WebChatConstants.APPID);
        logger.info("========================authurl=" + authurl);

//        mv.addObject("authurl", authurl);
        model.addAttribute("authurl", authurl);

        return mv;
    }

    @RequestMapping(value = "/test/yasuoimgcc/{mpid}")
    @ResponseBody
    public JsonDO yasuoimgcc(@PathVariable("mpid") Long mpid) throws Exception {
        JsonDO info = new JsonDO();
//        List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mpid","35"));
        List<Store> slist = storeService.selectList(new EntityWrapper<Store>().eq("mpid", mpid));
        String hurl = "";
        String ncdurl = "http://img.niucaiduo.com";
        String ncdurl2 = "https://img.niucaiduo.com";
        String localpre = "/fafa/www/images";

        // 先出里jpg|jpeg
// 先出里jpg|jpeg
        for (Store item : slist) {

            if (item.getPic() != null && (item.getPic().endsWith("jpg") || item.getPic().endsWith("jpeg"))) {
                if (item.getPic().startsWith("http://img.niucaiduo.com")) hurl = ncdurl;
                else if (item.getPic().startsWith("https://img.niucaiduo.com")) hurl = ncdurl2;
                else {
                    logger.info(">>>>>>>>>>>>>>>>>>>>改图片不在本机");
                    continue;
                }
                if (!Strings.isNullOrEmpty(item.getThumb())) continue;

                String ext = item.getPic().substring(item.getPic().lastIndexOf("."));// .jgp
                String noneext = item.getPic().substring(0, item.getPic().lastIndexOf("."));

                String localpath = item.getPic().replace(hurl, localpre);

                String bakpath = localpath.replace(ext, "") + "_bak" + ext;
                String nailpath = localpath.replace(ext, "") + "_nail" + ext;
                logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>localpath=" + localpath);
                logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>bakpath=" + bakpath);

                // 等比例缩小至0.25
                Thumbnails.of(localpath).scale(1f).outputQuality(0.5f).toFile(bakpath);
                Thumbnails.of(localpath).scale(0.5f).toFile(nailpath);

                try {
                    Runtime.getRuntime().exec("chmod 644 " + bakpath);
                } catch (IOException e) {
                    logger.error("chmod 644 " + bakpath + " error", e);
                }
                // 删除
                new File(localpath).delete();

                // 移动
                try {
                    String mvcmd = "mv " + bakpath + " " + localpath;
                    Runtime.getRuntime().exec(mvcmd);
                } catch (IOException e) {
                    logger.error("mv " + bakpath + " " + localpath, e);
                }

                Store ngoods = new Store();
                ngoods.setId(item.getId());
                ngoods.setThumb(nailpath.replace(localpre, hurl));
                ngoods.updateById();
                logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>Store update ok at gid=" + item.getId());
            }
        }

        return info;
    }

    @RequestMapping(value = "/test/yasuoimgbanner/{mpid}")
    @ResponseBody
    public JsonDO yasuoimgbanner(@PathVariable("mpid") Long mpid) throws Exception {
        JsonDO info = new JsonDO();
//        List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mpid","35"));
        List<Banner> slist = bannerService.selectList(new EntityWrapper<Banner>().eq("mpid", mpid));

        String hurl = "";
        String ncdurl = "http://img.niucaiduo.com";
        String ncdurl2 = "https://img.niucaiduo.com";
        String localpre = "/fafa/www/images";

        // 先出里jpg|jpeg
        for (Banner item : slist) {

            if (item.getPic() != null && (item.getPic().endsWith("jpg") || item.getPic().endsWith("jpeg"))) {
                if (item.getPic().startsWith("http://img.niucaiduo.com")) hurl = ncdurl;
                else if (item.getPic().startsWith("https://img.niucaiduo.com")) hurl = ncdurl2;
                else {
                    logger.info(">>>>>>>>>>>>>>>>>>>>改图片不在本机");
                    continue;
                }
//                if(!Strings.isNullOrEmpty(item.getThumb()))continue;

                String ext = item.getPic().substring(item.getPic().lastIndexOf("."));// .jgp
                String noneext = item.getPic().substring(0, item.getPic().lastIndexOf("."));

                String localpath = item.getPic().replace(hurl, localpre);

                String bakpath = localpath.replace(ext, "") + "_bak" + ext;
                logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>localpath=" + localpath);
                logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>bakpath=" + bakpath);

                // 等比例缩小至0.25
//                Thumbnails.of(localpath).scale(1f).outputQuality(0.5f).toFile(bakpath);
                Thumbnails.of(localpath).scale(0.5f).toFile(bakpath);

                try {
                    Runtime.getRuntime().exec("chmod 644 " + bakpath);
                } catch (IOException e) {
                    logger.error("chmod 644 " + bakpath + " error", e);
                }
                // 删除
                new File(localpath).delete();

                // 移动
                try {
                    String mvcmd = "mv " + bakpath + " " + localpath;
                    Runtime.getRuntime().exec(mvcmd);
                } catch (IOException e) {
                    logger.error("mv " + bakpath + " " + localpath, e);
                }
            }
        }

        return info;
    }

    @RequestMapping(value = "/test/yasuoimg/{uid}")
    @ResponseBody
    public JsonDO yasuoimg(@PathVariable("uid") Long uid) throws Exception {
        JsonDO info = new JsonDO();
        logger.info("====================/test/wxredirect coming and uid=" + uid);
        List<Goods> list = goodsService.selectList(new EntityWrapper<Goods>().eq("mpid", uid));
        String hurl = "";
        String ncdurl = "http://img.niucaiduo.com";
        String ncdurl2 = "https://img.niucaiduo.com";
        String localpre = "/fafa/www/images";

        // 先出里jpg|jpeg
        for (Goods item : list) {

            if (item.getPic() != null && (item.getPic().endsWith("jpg") || item.getPic().endsWith("jpeg"))) {
                if (item.getPic().startsWith("http://img.niucaiduo.com")) hurl = ncdurl;
                else if (item.getPic().startsWith("https://img.niucaiduo.com")) hurl = ncdurl2;
                else {
                    logger.info(">>>>>>>>>>>>>>>>>>>>改图片不在本机");
                    continue;
                }
                if (!Strings.isNullOrEmpty(item.getThumb())) continue;

                String ext = item.getPic().substring(item.getPic().lastIndexOf("."));// .jgp
                String noneext = item.getPic().substring(0, item.getPic().lastIndexOf("."));

                String localpath = item.getPic().replace(hurl, localpre);

                String bakpath = localpath.replace(ext, "") + "_bak" + ext;
                String nailpath = localpath.replace(ext, "") + "_nail" + ext;
                logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>localpath=" + localpath);
                logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>bakpath=" + bakpath);

                // 等比例缩小至0.25
//                Thumbnails.of(localpath).scale(1f).outputQuality(0.25f).toFile(bakpath);
                Thumbnails.of(localpath).scale(0.25f).toFile(nailpath);

                try {
                    Runtime.getRuntime().exec("chmod 644 " + bakpath);
                } catch (IOException e) {
                    logger.error("chmod 644 " + bakpath + " error", e);
                }
                // 删除
//                new File(localpath).delete();

                // 移动
//                try {
//                    String mvcmd = "mv " + bakpath +" "+localpath;
//                    Runtime.getRuntime().exec(mvcmd);
//                } catch (IOException e) {
//                    logger.error("mv " + bakpath +" "+localpath, e);
//                }

                Goods ngoods = new Goods();
                ngoods.setId(item.getId());
                ngoods.setThumb(nailpath.replace(localpre, hurl));
                ngoods.updateById();
                logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>Goods update ok at gid=" + item.getId());
            }
        }

        return info;
    }

    @RequestMapping(value = "/test/wxredirect/{uid}")
    public void wxredirect(@PathVariable("uid") String uid,
                           String code,
                           HttpServletRequest request,
                           HttpServletResponse response,
                           Model model) throws Exception {

        logger.info("====================/test/wxredirect coming and uid=" + uid);
        logger.info("====================/test/wxredirect coming and code=" + code);

        ModelAndView mv = new ModelAndView("test/userqr");

        String authurl = WebChatConstants.OAuth2_URL.replace("APPID", WebChatConstants.APPID)
                .replace("APPSECRET", WebChatConstants.APPSECRET).replace("CODE", code);

        String json = HttpUtils.httpGet(authurl);
        logger.info("====================json=" + json);

        model.addAttribute("uid", "29");

//        return mv;
    }

    @RequestMapping("/test/junlbao")
    @ResponseBody
    public Jinfo junlbao(@RequestParam("hkyid") long id) {
        Jinfo json = new Jinfo();
        Document zhensuo = null;

        logger.info("========================junlbao start");

        org.jsoup.nodes.Document doc = null;
        org.jsoup.nodes.Document subdoc = null;

        String rurl = "http://nfyx.jlbry.com";
        String url = "http://nfyx.jlbry.com/precision/pc/secret/member/index";
        for (Integer i = 1; i <= 13411; i++) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", ""));
            params.add(new BasicNameValuePair("startTime", ""));
            params.add(new BasicNameValuePair("endTime", ""));
            params.add(new BasicNameValuePair("topage", i.toString()));
            params.add(new BasicNameValuePair("actionType", "0"));
            params.add(new BasicNameValuePair("page", "1"));
            params.add(new BasicNameValuePair("pageSize", "10"));
            String result = HttpUtils.httpPostWithCookie(url, params);
            logger.info("========================result 111111");

            if (!Strings.isNullOrEmpty(result)) {
                doc = Jsoup.parse(result);
                Elements trs = doc.getElementsByClass("text-c");
                if (trs.size() != 11) break;
                int m = -1;
                for (Element tr : trs) {
                    if (m == -1) {
                        m++;
                        continue;
                    } else {
                        m++;
                    }
                    logger.debug("========================ele=" + tr.outerHtml());
                    Elements tds = tr.getElementsByTag("td");
                    Kehu kehu = new Kehu();

                    kehu.setMname(tds.get(4).text());
                    kehu.setName(tds.get(0).text());
                    kehu.setPhone(tds.get(1).text());

                    // /precision/pc/secret/member/detail?memberId=100000186854
                    String detailurl = tds.get(5).getElementsByTag("a").get(0).attr("href");

                    params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("name", ""));

                    String sub = HttpUtils.httpGetWithCookie(rurl + detailurl, params);
                    logger.info("========================result 222222");

                    subdoc = Jsoup.parse(sub);
                    Elements divs = tr.getElementsByClass("padb");

                    if (divs != null && divs.size() > 0) {
                        kehu.setArea(divs.get(3).text().replaceAll("&nbsp;", "")
                                .replaceAll("省份：", ""));
                        kehu.setShi(divs.get(4).text().replaceAll("&nbsp;", "")
                                .replaceAll("市：", ""));
                        Area area2 = areaService.selectOne(new EntityWrapper<Area>()
                                .setSqlSelect("name,code,sheng")
                                .like("name", kehu.getArea())
                                .eq("level", '1'));

                        logger.info("========================area2 =" + area2);

                        if (area2 != null) {
                            kehu.setAreacode(area2.getCode());

                            String sh = area2.getCode().substring(0, 2);
                            Area shi2 = areaService.selectOne(new EntityWrapper<Area>()
                                    .setSqlSelect("name,code,sheng")
                                    .like("name", kehu.getShi())
                                    .eq("sh", sh));
                            if (shi2 != null) {
                                kehu.setShicode(shi2.getCode());
                            }
                        }
                    }

                    kehu.setHyname("宝妈");
                    kehu.setHyname("宝妈");

                    kehu.setHyname("宝妈");
                    kehu.setHytype("baoma");
                    kehu.setState(1);
                    kehu.setCreatetime(new Date());
                    kehu.insert();

                    logger.info("========================kehu insert ok");

//                    break;
                }
            }
//            break;
        }

        return json;
    }


    @RequestMapping("/test/kouqiangzhuaqu")
    @ResponseBody
    public Jinfo kouqiangzhuaqu(@RequestParam("hkyid") long id) {
        Jinfo json = new Jinfo();
        Document zhensuo = null;

        org.jsoup.nodes.Document doc = null;
        String date = null;
        String rurl = "http://www.kqzp.cn";
        String urlgun = "http://www.kqzp.cn/31/";
        boolean hasNew = false;

        // 抓取口腔客户资料
//        for(int i =0;i<urls.size();i++) {
        logger.debug(">>>>>> kouqiangzhuaqu for url=" + urlgun);
        String result = HttpUtils.httpGet(urlgun);
        logger.debug("========================result 111");

        String url = null;
        Map<String, String> shimap = new HashMap();
        int sheng = 0;
        if (!Strings.isNullOrEmpty(result)) {
            doc = Jsoup.parse(result);
            Element ele = doc.getElementsByClass("qu2").get(0);
            logger.debug("========================ele=" + ele.outerHtml());

            Elements zlinks = ele.getElementsByTag("a");

            for (Element link : zlinks) {
                sheng++;
                if (sheng < 6) {
                    continue;
                }
                String area = link.text();
                Area area2 = areaService.selectOne(new EntityWrapper<Area>()
                        .setSqlSelect("name,code,sheng")
                        .like("name", area)
                        .eq("level", '1'));

                String zhixias = "110000,120000,310000,500000";

                List<Area> shi = new ArrayList<>();
                String sh = area2.getCode().substring(0, 2);
                if (zhixias.indexOf(area2.getCode()) >= 0) {
                    // 直辖市
                    shi = areaService.selectList(new EntityWrapper<Area>().eq("level", 3).eq("sheng", sh));
                } else {
                    // 非直辖
                    shi = areaService.selectList(new EntityWrapper<Area>().eq("level", 2).eq("sheng", sh));
                }
                shimap.clear();
                for (Area item : shi) {
                    shimap.put(item.getName().replace("市", ""), item.getCode());
                }

                for (int idx = 1; idx < 10000; idx++) {

                    url = urlgun + link.attr("href").replace("/31", "") + idx + ".htm";
                    logger.debug("========================url=" + url);
                    result = HttpUtils.httpGet(url);
                    logger.debug("========================result 222");

                    doc = Jsoup.parse(result);
                    Elements pkuais = doc.getElementsByClass("pkuai");
                    if (pkuais == null || pkuais.size() == 0) break;

                    for (Element pkuai : pkuais) {
                        Kehu kehu = new Kehu();

                        Element lvv = pkuai.getElementsByClass("lvv").get(0);

                        kehu.setName(pkuai.getElementsByClass("l6").get(0).text()
                                .replaceAll("联系我们", "").replaceAll("联系人：", ""));
                        kehu.setMname(pkuai.getElementsByClass("l1").get(0).text());

                        kehu.setName(kehu.getName().trim().replaceAll("　", "").replaceAll(" ", ""));
                        kehu.setMname(kehu.getMname().trim().replaceAll("VIP", "").replaceAll("　", "").replaceAll(" ", ""));

                        kehu.setArea(area);
                        if (area2 != null) kehu.setAreacode(area2.getCode());

                        if (lvv == null) continue;

                        String suburl = rurl + lvv.getElementsByTag("a").get(0).attr("href");
                        logger.debug("========================suburl=" + suburl);
                        try {
                            result = HttpUtils.httpGet(suburl);
                        } catch (Exception e) {
                            logger.debug("=====================================================result 333 error");
                            continue;
                        }
                        logger.debug("=====================================================result 333");

                        zhensuo = Jsoup.parse(result);
                        Element lxfstab = zhensuo.getElementById("lxfstab");

                        if (lxfstab == null) continue;
                        logger.debug("======================================result 555");

                        Elements rows = lxfstab.getElementsByTag("tr");
                        for (int m = 0; m < rows.size(); m++) {
                            logger.debug("=======================================================================rows.get(m)=" + rows.get(m));
                            if (m == 0) {
                                kehu.setAddress(rows.get(m).getElementsByTag("a").get(0).text());
                                kehu.setAddress(kehu.getAddress().replaceAll("。", "").replaceAll("　", "").replaceAll(" ", ""));
                            } else if (m == 2) {
                                kehu.setPhone(rows.get(m).getElementsByClass("tel") == null ||
                                        rows.get(m).getElementsByClass("tel").size() == 0 ? "" : rows.get(m).getElementsByClass("tel").get(0).text());
                            } else if (m == 3) {
                                kehu.setTelephone(rows.get(m).getElementsByClass("tel") == null ||
                                        rows.get(m).getElementsByClass("tel").size() == 0 ? "" : rows.get(m).getElementsByClass("tel").get(0).text());
                            } else if (m == 4) {
                                kehu.setEmail(rows.get(m).getElementsByTag("span") == null ||
                                        rows.get(m).getElementsByTag("span").size() == 0 ? "" : rows.get(m).getElementsByTag("span").get(0).text());
                            } else if (m == 5) {
                            } else if (m == 6) {
                                kehu.setWebsite(rows.get(m).getElementsByTag("th") == null ||
                                        rows.get(m).getElementsByTag("th").size() == 0
                                        ? "" : rows.get(m).getElementsByTag("th").get(0).text());
                            }
                        }

                        kehu.setWebsite(kehu.getWebsite().replaceAll("　", "").replaceAll(" ", ""));
                        Wrapper<Kehu> wrapper = new EntityWrapper<Kehu>().eq("address", kehu.getAddress());

//                        int kehuone = kehuService.selectCount(wrapper);
//                        if (kehuone > 0&& kehu.getAddress().length()>0) {
//                            logger.debug("========================result 222 kehuone>0 and continue");
//                            continue;
//                        }

                        for (Area item : shi) {
                            String shortshi = item.getName().replace("市", "");
                            if (kehu.getAddress() != null && kehu.getAddress().indexOf(shortshi) >= 0) {
                                kehu.setShicode(item.getCode());
                                kehu.setShi(item.getName());
                            }
                        }

                        kehu.setHyname("口腔");
                        kehu.setHytype("kouqiang");
                        kehu.setState(1);
                        kehu.setCreatetime(new Date());
                        kehu.insert();
                    }

                    Elements pagealink = doc.getElementsByClass("page").get(0).getElementsByTag("a");
                    if (!pagealink.get(pagealink.size() - 1).text().equals("下一页")) {
                        break;
                    }
                }
            }
        }

        return json;
    }


}
